package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDTO;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.NewsAuthDTO;
import com.heima.model.wemedia.dto.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.common.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>implements WmNewsService {


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Value("${file.oss.web-site}")
    String webSite;

    /*
    * TODO 分页待条件查询自媒体文章列表
    *   需求
    *  1. 如果有文章标题，按照文章标题模糊查询
       2. 如果有频道信息，按照频道ID查询
       3. 如果有文章状态，按照状态信息进行查询
       4. 如果开始时间，结束时间不为空按照时间区间查询
       5. 按照登录用户ID去查询
       6. 按照创建时间降序
       7. 分页查询，返回结果设置host  地址 为图片访问前缀
    *  */
    @Override
    public ResponseResult queueList(WmNewsPageReqDTO dto) {
        //TODO 参数检查 检查分页
        dto.checkParam();
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        }
        //TODO 检查是否登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录");
        }

        //TODO 2. 封装查询条件
        LambdaQueryWrapper<WmNews> lambdaQuery = Wrappers.lambdaQuery();
        //TODO 2.1 分页条件
        IPage<WmNews> pageRe = new Page<>(dto.getPage(), dto.getSize());
        //TODO 2.2 如果有文章标题，按照文章标题模糊查询
        //todo 标题判断是否存在
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQuery.like(WmNews::getTitle, dto.getKeyword());
        }
        //TODO 2.3 如果有频道信息，按照频道ID查询  频道    eq == 频道id
        lambdaQuery.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //TODO 2.4 如果有文章状态，按照状态信息进行查询  状态    eq
        lambdaQuery.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //TODO 如果开始时间，结束时间不为空按照时间区间查询
        //TODO 2.5 大于等于 开始时间
        lambdaQuery.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        //TODO  小于等于 结束时间
        lambdaQuery.eq(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        //TODO 2.6 按照登录用户ID去查询 用户过滤条件   eq == user_id
        lambdaQuery.eq(WmNews::getUserId, user.getId());
        //TODO 2.7  按照创建时间降序 时间降序
        lambdaQuery.orderByDesc(WmNews::getPublishTime);
        //TODO 3.执行查询
        IPage<WmNews> pageResult = this.page(pageRe, lambdaQuery);
        //TODO 4.封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());

        //TODO 分页查询，返回结果设置host  地址 为图片访问前缀
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    /**
     * 自媒体文章发布
     *
     * @param wmNewsDto
     * @return
     */
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDTO wmNewsDto) {

        //TODO 1 参数校验
        //todo 1.1.0 检查内容
        if (wmNewsDto == null || StringUtils.isBlank(wmNewsDto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        //todo 1.1.1 检查状态
        Short status = wmNewsDto.getStatus();
        if (!WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(status) && !WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章状态异常");
        }
        //todo 1.1.2 检查用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录");
        }
        //todo 将dto拷贝属性到wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //todo 设置封面自动，若是自动则将type设为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())) {
            wmNews.setType(null);
        }
        //todo images数组转为字符串
        List<String> imagesList = wmNewsDto.getImages();//todo 获取图片集合
        //判断集合是否为空
        if (CollectionUtils.isNotEmpty(imagesList)) {
            wmNews.setImages(imageListToStr(imagesList));
        }
        //todo 用户登录
        wmNews.setUserId(user.getId());
        //TODO 2 保存或修改文档
        saveOrUpdateByWmNews(wmNews);
        //todo  2.4 如果审核状态为1，发送消息到kafa等到审核
        if (WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)) {
            return ResponseResult.okResult();
        }
        //TODO 3 设置文章和素材的关联
        //todo 3.1 文章内容中抽取图片列表 parseContentlmages
        List<String> imageList = parseContentlmages(wmNews.getContent());

        //todo 3.2 判断如果不是草稿，设置抽取图片与素材关联关系
        // 保存文章内容和素材的关联关系saveRelativeInfo
        if (CollectionUtils.isNotEmpty(imageList)) {
            //引用素材url列表   文章id 引用类型
            saveRelativeInfo(imageList, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //todo 3.3 设置封面图片和素材之间的关联关系saveRelativeInfoForCover
        //封面的选择有两种：自动或无图
        saveRelativeInfoForCover(wmNewsDto, wmNews, imageList);

        //todo 3.4 发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, wmNews.getId());

        return ResponseResult.okResult();
    }

    /**
     * 生成封面内容 并保存封面和素材的关系
     *
     * @param wmNewsDto
     * @param wmNews
     * @param imageList
     */
    private void saveRelativeInfoForCover(WmNewsDTO wmNewsDto, WmNews wmNews, List<String> imageList) {
        //todo 获取封面列表
        List<String> images = wmNewsDto.getImages();
        //todo 判断封面生成的类型 -1自动生成
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())) {
            //todo 图片数量大于2为多图类型
            if (imageList.size() > 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imageList.stream().limit(3).collect(Collectors.toList());
            } else if (imageList.size() > 0 && imageList.size() <= 2) {
                //todo 0<图片数量<=2为单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imageList.stream().limit(1).collect(Collectors.toList());
            } else {
                //todo 其他情况为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            }
            //todo 将图片数组转为字符串保存到images字段中
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imageListToStr(images));
            }
            //todo 修改文章信息
            updateById(wmNews);
        }
        //todo 判断最终封面集合是否为空
        if (CollectionUtils.isNotEmpty(images)) {
            images.stream().map(url -> url.replaceAll(webSite, ""))
                    .collect(Collectors.toList());
            //todo 保存封面和素材之间的关联关系
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }

    }

    /*
     * todo 图片集合转为字符串
     *    images 图片列表
     *    webSite 图片前缀
     *   分析多个图片用逗号拼接，去除图片路径的前缀
     *  */
    private String imageListToStr(List<String> imagesList) {
        return imagesList.stream().map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));//todo 使用逗号拼接成字符串
    }

    /*
     * TODO 保存或修改文档
     *   如果id为空则保存文档
     *   如果id不为空则修改--》删除素材与文档之间的联系，修改文档
     *  */
    private void saveOrUpdateByWmNews(WmNews wmNews) {
        //todo 补全WmNews信息 添加提交时间
        wmNews.setSubmitedTime(new Date());
        if (wmNews.getId() == null) {
            //todo 补全文档创建时间
            wmNews.setCreatedTime(new Date());
            this.save(wmNews);//todo 保存文档
        } else {
            //todo id不为空则修改--》
            // 删除素材与文档之间的联系，修改文档
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //todo 修改文档
            this.updateById(wmNews);
        }
    }

    /*
     * todo  抽取文章中关联的所有图片
     *  */
    private List<String> parseContentlmages(String content) {
        List<Map> maps = JSON.parseArray(content, Map.class);
        return maps.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE
                .equals(map.get("type")))   //todo 过滤type=image对应的数据
                .map(map -> (String) map.get("value")) //todo 获取数据中的value部分：图片url路径
                .map(url -> url.replaceAll(webSite, ""))  //去除路径前缀
                .collect(Collectors.toList()); //todo 将数据搜集到集合
    }

    /**
     * 保存素材和文章的关系
     *
     * @param imageList          图片集合  select *from wm_mater where url in (url1, url2, url3)and user_id = ?
     * @param id
     * @param wmContentReference
     */
    private void saveRelativeInfo(List<String> imageList, Integer id, Short wmContentReference) {
        //todo 根据图片列表及用户id获取素材列表
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, imageList)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的素材不存在");
        }
        //todo 将素材列表转为map集合 key为图片url value为素材id
        Map<String, Integer> urlMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        //todo 遍历集合判断所有图片在素材中是否存在 并将存在的id保存到集合中
        ArrayList<Integer> materialId = new ArrayList<>();
        for (String materialUrl : imageList) {
            if (!urlMap.containsKey(materialUrl)) {//判定urlMap集合中是否包含key为materialUrl的键
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的url不存在");
            }
            //todo 得到存在的素材id列表，与newsId及type进行批量保存
            materialId.add(urlMap.get(materialUrl));
        }
        wmNewsMaterialMapper.saveRelations(materialId, id, wmContentReference);
    }

    /*
     * todo 根据id查询文章
     *  */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //TODO 检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "id不能为空");
        }
        //todo 执行查询
        WmNews user = this.getById(id);
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(webSite);
        return result;
    }

    /*
     * todo 根据文章ID删除文章
     *  */
    @Override
    public ResponseResult deleteById(Integer id) {
        //todo 检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        //todo 执行查询
        WmNews user = this.getById(id);
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询的文章不存在");
        }
        //todo 判断当前文章的状态  status==9  enable == 1不能删除其他状态可以删除
        if (user.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) &&
                WemediaConstants.WM_NEWS_UP.equals(user.getEnable())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "此状态下文章不能删除，请先下架");
        }
        //todo 去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, user.getId()));
        //todo 删除文章
        removeById(user.getId());
        return ResponseResult.okResult();
    }

    /*
     * TODO 文章上下架操作
     *  */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //TODO 1 检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //todo 2查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询的文章不存在");
        }
        //todo 3 获取当前文章的上下架情况
        Short enable = dto.getEnable();
        if (enable == null || !WemediaConstants.WM_NEWS_UP.equals(enable) &&
                !WemediaConstants.WM_NEWS_DOWN.equals(enable)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章上下架状态错误");
        }
        //todo 4 判断文章是否发布 9 发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前文章不处于发布状态，不能下架");
        }
        //todo 5 修改文章状态，同步到app端（后期做）
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, enable));

        //TODO 6 上下架发送消息通知  用于同步article 及 elasticsearch
        if (enable.equals(WemediaConstants.WM_NEWS_UP)&&wmNews.getArticleId()!=null){
            //发布上架消息
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
        }else {
            //发布下架消息
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId());

        }
        return ResponseResult.okResult();
    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //todo 检查参数
        dto.checkParam();
        //todo 记录当前页
        Integer currentPage = dto.getPage();
        Integer size = dto.getSize();
        //todo 设置起始页
        dto.setPage((currentPage - 1) * size);
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }
        //todo 分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        //todo 统计多少条数据
        long count = wmNewsMapper.findListCount(dto);
        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVOList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据文章id查询文章详情
     *
     * @param id
     * @return
     */
    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVO(Integer id) {
        //todo 检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "id不能为空");
        }
        //todo 查询文章信息
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //todo 查询文章作者
        Integer userId = wmNews.getUserId();
        WmUser wmUser = null;
        if (userId != null) {
            wmUser = wmUserMapper.selectById(userId);
        }
        //4.封装vo信息返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        if (wmUser != null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(webSite);
        return result;
    }


    /**
     * 自媒体文章人工审核
     *
     * @param dto
     * @param status 2  审核失败  4 审核成功
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {

        //todo 1.参数检查
        if (dto == null || dto.getId() == null) {
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //TODO 2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //todo 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章
        if (status.equals(WmNews.Status.ADMIN_AUTH.getCode())){
            //通知定时发布
            long publishTime = wmNews.getPublishTime().getTime();//发布时间
            //当前时间
            long noeTime = new Date().getTime();
            long remainTime = publishTime - noeTime;
            if (remainTime<=0){
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                        ,PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                        ,wmNews.getId()
                );
                log.info("立即发布文章通知成功发送，文章id : {}",wmNews.getId());
            }else {
                // 延时发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                        , PublishArticleConstants.PUBLISH_ARTICLE_DEAD_ROUTE_KEY
                        , wmNews.getId()
                        , (message)-> {
                            message.getMessageProperties().setExpiration(String.valueOf(remainTime));
                            return message;
                        }
                );
                log.info("延时发布文章通知成功发送，文章id : {} , 延时时间: {}毫秒",wmNews.getId(),remainTime);
            }
        }
        return ResponseResult.okResult();
    }
}

